﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using JohnnySins.DAL;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;
using JohnnySins.Code;
using System.Globalization;

namespace JohnnySins.Admin
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FindSelected();

            if (!IsPostBack)
            {
                LoadNextLiveShow();
                LoadWelcomeNote();
                LoadRecentScene();
                LoadBanner();
            }
        }

        public int[] Selected { get; set; }

        private void FindSelected()
        {
            var selected = new List<int>();

            foreach (GridViewRow row in grid.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var check = row.Cells[0].FindControl("cbSelected") as CheckBox;
                    if (check.Checked)
                    {
                        var id = row.FindControl("hidId") as HiddenField;
                        selected.Add(int.Parse(id.Value));
                    }
                }
            }

            Selected = selected.ToArray();
        }

        private void LoadNextLiveShow()
        {
            using (var repo = RepositoryFactory.ResolveRepository<NextLiveShowRepository>())
            {
                gridNextLiveShow.DataSource = repo.FindAll();
                gridNextLiveShow.DataBind();
            }
        }

        protected void LoadWelcomeNote()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ParameterSiteRepository>())
            {
                txtWelcomeNote.Text = "";
                ParameterSite itm = repo.Find("WelcomeNote");
                if ((itm != null) && (!string.IsNullOrEmpty(itm.ParameterValueStr)))
                    txtWelcomeNote.Text = itm.ParameterValueStr;
            }
        }

        protected void LoadRecentScene()
        {
            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                grid.DataSource = repo.FindAll();
                grid.DataBind();
            }
        }

        protected void LoadBanner()
        {
            using (var repo = RepositoryFactory.ResolveRepository<BannerRepository>())
            {
                gridBanner.DataSource = repo.FindAll("Home");
                gridBanner.DataBind();
            }
        }

        protected void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                RecentScene item = (RecentScene)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("btnDeactivate");
                ibtn.Visible = item.IsActive;

                ibtn = (ImageButton)e.Row.FindControl("btnActivate");
                ibtn.Visible = !item.IsActive;

                CheckBox cbSelected = (CheckBox)e.Row.FindControl("cbSelected");
                cbSelected.Checked = Selected.Contains(item.RecentSceneId);
            }

            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox chbAll = (CheckBox)e.Row.FindControl("chbAll");
                chbAll.Checked = (Selected.Length == (grid.DataSource as IEnumerable<RecentScene>).Count());
            }
        }

        protected void grid_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            if (e.CommandName == "delete")
            {
                DeleteScene(id);
            }
            else
            {
                using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
                {
                    switch (e.CommandName)
                    {
                        case "deactivate":
                            repo.Deactivate(id);
                            break;
                        case "activate":
                            repo.Activate(id);
                            break;
                    }
                }
            }

            LoadRecentScene();
        }

        protected void gridBanner_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Banner item = (Banner)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("btnDeactivate");
                ibtn.Visible = item.IsActive;

                ibtn = (ImageButton)e.Row.FindControl("btnActivate");
                ibtn.Visible = !item.IsActive;
            }
        }

        protected void gridBanner_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            if (e.CommandName == "deleteBanner")
            {
                DeleteBanner(id);
            }
            else
            {
                using (var repo = RepositoryFactory.ResolveRepository<BannerRepository>())
                {
                    switch (e.CommandName)
                    {
                        case "deactivate":
                            repo.Deactivate(id);
                            break;
                        case "activate":
                            repo.Activate(id);
                            break;
                    }
                }
            }

            LoadBanner();
        }

        protected void gridNextLiveShow_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                NextLiveShow item = (NextLiveShow)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("btnDeactivate");
                ibtn.Visible = item.IsActive;

                ibtn = (ImageButton)e.Row.FindControl("btnActivate");
                ibtn.Visible = !item.IsActive;
            }
        }

        protected void gridNextLiveShow_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            if (e.CommandName == "delete")
            {
                DeleteNextLiveShow(id);
            }
            else
            {
                using (var repo = RepositoryFactory.ResolveRepository<NextLiveShowRepository>())
                {
                    switch (e.CommandName)
                    {
                        case "deactivate":
                            repo.Deactivate(id);
                            break;
                        case "activate":
                            repo.Activate(id);
                            break;
                    }
                }
            }

            LoadNextLiveShow();
        }

        protected void DeleteScene(int id)
        {
            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                RecentScene itm = repo.Find(id);
                if (itm != null)
                {
                    string path = Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysFileName);
                    BasePage.DeleteFile(path);
                    path = Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysPoster);
                    BasePage.DeleteFile(path);

                    repo.Delete(id);
                }
            }
        }

        protected void DeleteBanner(int id)
        {
            using (var repo = RepositoryFactory.ResolveRepository<BannerRepository>())
            {
                Banner itm = repo.Find(id);
                if (itm != null)
                {
                    string path = Path.Combine(Server.MapPath("~/Files/ImageBanner/Home"), itm.PhysFileName);
                    if (File.Exists(path))
                        try
                        {
                            File.Delete(path);
                        }
                        catch (Exception ex) { }
                    repo.Delete(id);
                }
            }
        }

        protected void DeleteNextLiveShow(int id)
        {
            using (var repo = RepositoryFactory.ResolveRepository<NextLiveShowRepository>())
            {
                repo.Delete(id);
            }
        }

        protected void upDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upDetails.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdId.Text = Request["__EVENTARGUMENT"];

                fuRecentSceneFileName.Clear();
                fuPoster.Style.Clear();

                if (hdId.Text != "-1")
                {
                    using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
                    {
                        lblDialogTitle.Text = "EDIT RECENT SCENE";
                        RecentScene itm = repo.Find(Convert.ToInt32(hdId.Text));
                        txtRecentSceneTitle.Text = itm.RecentSceneTitle;
                        ddlIsActive.SelectedValue = itm.IsActive ? "1" : "0";

                        if (!string.IsNullOrEmpty(itm.RecentSceneFileName))
                        {
                            fuRecentSceneFileName.FileName = itm.RecentSceneFileName;
                        }
                        
                        if (!string.IsNullOrEmpty(itm.Poster))
                        {
                            fuPoster.Style.Add("display", "none");
                            pnlPoster.Visible = true;
                            lblPoster.Text = itm.Poster;
                            hdPoster.Value = "0";
                        }
                        else
                        {
                            pnlPoster.Visible = false;
                            hdPoster.Value = "1";
                        }

                    }
                }
                else
                {
                    lblDialogTitle.Text = "ADD NEW RECENT SCENE";

                    txtRecentSceneTitle.Text = "";
                    ddlIsActive.SelectedValue = "1";

                    fuPoster.Visible = true;
                    pnlPoster.Visible = false;
                }

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "$('#editDialog').dialog('open');", true);
            }
        }

        protected void upNextLiveShowDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upNextLiveShowDetails.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdNextLiveShowId.Text = Request["__EVENTARGUMENT"];

                if (hdNextLiveShowId.Text != "-1")
                {
                    using (var repo = RepositoryFactory.ResolveRepository<NextLiveShowRepository>())
                    {
                        lblNextLiveShowDialogTitle.Text = "EDIT NEXT LIVE SHOW INFO";
                        NextLiveShow itm = repo.Find(Convert.ToInt32(hdNextLiveShowId.Text));
                        txtNextLiveShowName.Text = itm.NextLiveShowName;
                        txtNextLiveShowDate.Text = itm.NextLiveShowDate.ToString("d", new CultureInfo("en-US"));
                        txtNextLiveShowTime.Text = itm.NextLiveShowDate.ToString("HH:mm");
                        ddlNextLiveShowState.SelectedValue = itm.IsActive ? "1" : "0";
                    }
                }
                else
                {
                    lblNextLiveShowDialogTitle.Text = "ADD NEXT LIVE SHOW INFO";

                    txtNextLiveShowName.Text = "";
                    txtNextLiveShowDate.Text = DateTime.Today.Date.ToString("d", new CultureInfo("en-US"));
                    txtNextLiveShowTime.Text = DateTime.Now.ToString("HH:mm");
                    ddlNextLiveShowState.SelectedValue = "1";
                }

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "$('#editNextLiveShow').dialog('open');", true);
            }
        }

        protected void btnBannerUpload_Click(object sender, EventArgs e)
        {
            if (!fuBanner.HasFile)
                return;

            Banner itm = new Banner();
            itm.BannerFileName = fuBanner.FileName;
            itm.IsActive = true;
            itm.PageName = "Home";

            using (var repo = RepositoryFactory.ResolveRepository<BannerRepository>())
            {
                repo.Insert(itm);

                string filePath = Path.Combine(Server.MapPath("~/Files/ImageBanner/Home"), itm.PhysFileName);
                fuBanner.SaveAs(filePath);
            }
            LoadBanner();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (hdId.Text == "-1")
                if (!fuRecentSceneFileName.HasFile)
                    return;

            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                if (hdId.Text == "-1")
                {
                    RecentScene itm = new RecentScene();

                    itm.RecentSceneTitle = txtRecentSceneTitle.Text;
                    itm.IsActive = ddlIsActive.SelectedValue == "1";

                    itm.RecentSceneFileName = fuRecentSceneFileName.FileName;
                    itm.Poster = fuPoster.FileName;

                    repo.Insert(itm);

                    if (fuRecentSceneFileName.HasFile)
                    {
                        string filePath = Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysFileName);
                        fuRecentSceneFileName.SaveAs(filePath);
                    }
                    if (fuPoster.HasFile)
                    {
                        string filePath = Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysPoster);
                        fuPoster.SaveAs(filePath);
                    }
                }
                else
                {
                    RecentScene itm = repo.Find(Convert.ToInt32(hdId.Text));

                    itm.RecentSceneTitle = txtRecentSceneTitle.Text;
                    itm.IsActive = ddlIsActive.SelectedValue == "1";

                    if (fuRecentSceneFileName.IsNewFile)
                    {

                        BasePage.DeleteFile(Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysFileName));
                        itm.RecentSceneFileName = "";
                        if (fuRecentSceneFileName.HasFile)
                        {
                            itm.RecentSceneFileName = fuRecentSceneFileName.FileName;
                            string filePath = Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysFileName);
                            fuRecentSceneFileName.SaveAs(filePath);
                        }
                    }
                    if (hdPoster.Value == "1")
                    {
                        BasePage.DeleteFile(Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysPoster));
                        itm.Poster = "";
                        if (fuPoster.HasFile)
                        {
                            itm.Poster = fuPoster.FileName;
                            string filePath = Path.Combine(Server.MapPath("~/Files/RecentScenes"), itm.PhysPoster);
                            fuPoster.SaveAs(filePath);
                        }
                    }

                    repo.Update(itm);
                }
            }
            LoadRecentScene();
        }

        protected void upWelcomeNote_Load(object sender, EventArgs e)
        {
        }

        protected void btnSaveWelcomeNote_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<ParameterSiteRepository>())
            {
                repo.Edit(new ParameterSite() { ParameterName = "WelcomeNote", ParameterValueStr = txtWelcomeNote.Text });
            }
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", string.Format("alert('{0}');", "Welcome Note saved"), true);
        }

        protected void btnCancelWelcomeNote_Click(object sender, EventArgs e)
        {
            LoadWelcomeNote();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                foreach (int id in Selected)
                {
                    DeleteScene(id);
                }
            }

            LoadRecentScene();
        }

        protected void btnActivateSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                foreach(int id in Selected)
                {
                    repo.Activate(id);
                }
            }

            LoadRecentScene();
        }

        protected void btnDeactivateSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                foreach (int id in Selected)
                {
                    repo.Deactivate(id);
                }
            }

            LoadRecentScene();
        }

        protected void btnReverseSelected_Click(object sender, EventArgs e)
        {
            var otherScenes = new List<int>();

            using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
            {
                foreach (var scene in repo.FindAll())
                {
                    if (!Selected.Contains(scene.RecentSceneId))
                    {
                        otherScenes.Add(scene.RecentSceneId);
                    }
                }
            }

            Selected = otherScenes.ToArray();
            LoadRecentScene();
        }

        protected void btnNextLiveShowSave_Click(object sender, EventArgs e)
        {
            NextLiveShow itm = new NextLiveShow();
            itm.NextLiveShowName = txtNextLiveShowName.Text;
            try
            {
                itm.NextLiveShowDate = DateTime.ParseExact(txtNextLiveShowDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception e1)
            {
                lblNexLiveShowMessage.Text = "Date not valid!";
                return;
            }
            try
            {
                itm.NextLiveShowDate = itm.NextLiveShowDate + TimeSpan.Parse(txtNextLiveShowTime.Text);
            }
            catch (Exception e2)
            {
                lblNexLiveShowMessage.Text = "Time not valid!";
                return;
            }
            
            itm.IsActive = (ddlNextLiveShowState.SelectedValue == "1");

            using (var repo = RepositoryFactory.ResolveRepository<NextLiveShowRepository>())
            {
                if (hdNextLiveShowId.Text == "-1")
                {
                    repo.Insert(itm);
                }
                else
                {
                    itm.NextLiveShowId = Convert.ToInt32(hdNextLiveShowId.Text);
                    repo.Update(itm);
                }
            }
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "HideNextLiveShowDialog", "$('#editNextLiveShow').dialog('close');", true);
            LoadNextLiveShow();
            upNextLiveShow.Update();
        }

        protected void btnNextLiveShowCancel_Click(object sender, EventArgs e)
        {
            LoadNextLiveShow();
        }

        protected void chbAll_CheckChanged(Object sender, EventArgs e)
        {
            bool chk = (sender as CheckBox).Checked;
            if (chk)
            {
                var other = new List<int>();
                using (var repo = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
                {
                    foreach (var scene in repo.FindAll())
                        other.Add(scene.RecentSceneId);
                }

                Selected = other.ToArray();
            }
            else
                Selected = new int[] { };

            LoadRecentScene();
        }
    }
}